/*
 * Copyright (c) 2022 Kirky
 * Licensed under the Open Software Licence, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://opensource.org/licenses/osl-3.0.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lingeringdream.luciole.helper.identity;

import com.lingeringdream.luciole.helper.HttpHelper;
import com.mindspore.MSTensor;
import com.mindspore.Model;
import com.mindspore.config.CpuBindMode;
import com.mindspore.config.DeviceType;
import com.mindspore.config.MSContext;
import com.mindspore.config.ModelType;
import ohos.agp.colors.RgbColor;
import ohos.app.Context;
import ohos.global.resource.RawFileDescriptor;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.Image;
import ohos.media.image.ImageReceiver;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.ImageFormat;
import ohos.media.image.common.Position;
import ohos.media.image.common.Size;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;

/**
 * @author Kirky
 * @version 1.0
 * @date 2022/4/30
 */
public class IdentityHelper {
    private final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x0023, IdentityHelper.class.getSimpleName());
    private final Context context;
    private Model model;
    private boolean modelBuild = false;

    public IdentityHelper(Context context) {
        this.context = context;
        if (model == null) {
            initModel("entry/resources/rawfile/mobilenetv2.ms");
            if (model == null) {
                HiLog.error(TAG, "model is null!");
            }
        }
    }

    public Map<Float, String> byUrl(ImageReceiver imageReceiver) {
        String url = "https://2be63af20dca4b788a4c41b1efa24018.apig.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oiS2lya3ktWCIsImlkIjoiMDk2ZTk5MTBjNDAwMGY3ZTBmM2JjMDBjODEyOTI4NjAifSwibmFtZSI6Iktpcmt5LVgiLCJwYXNzd29yZF9leHBpcmVzX2F0IjoiIiwiaWQiOiIwOTZlOTkxMWI3MDBmNTZhMWYwMGMwMGM0OTQxY2ZlOCJ9fX0xggHBMIIBvQIBATCBlzCBiTELMAkGA1UEBhMCQ04xEjAQBgNVBAgMCUd1YW5nRG9uZzERMA8GA1UEBwwIU2hlblpoZW4xLjAsBgNVBAoMJUh1YXdlaSBTb2Z0d2FyZSBUZWNobm9sb2dpZXMgQ28uLCBMdGQxDjAMBgNVBAsMBUNsb3VkMRMwEQYDVQQDDApjYS5pYW0ucGtpAgkA3LMrXRBhahAwCwYJYIZIAWUDBAIBMA0GCSqGSIb3DQEBAQUABIIBAI0dBvow+4S1Vl4T0YRXjmXqZDpamMgCJ-w9JnPt3TjMF+4l47I3k-uaLd8tyPpCRyJ45UqNjmMXzXkluXFtmNIeGF8pOUVSnZK-piNKvqZNRXVctLg7wuDxI+EgMObtnCjEzucNB-DnHEgb2WyPbuMDUSiAhy4kLCvMQnJHraHPeIUbxgh8OebtzgYwqwqaMIuNayyCuS4Lzj0nwGBJ5TwPXBrRWsQp0QPfQY8yG2vfKxKRoIsiv5eTzr671NZJWD3NtRAqSmxYGlb4NWuArnSBgRgQkVPUmYSZEYCZ0EezE4NBwKRufK8Ov9OydGVuPM-X5P4kmFXMVR0lqmzqb+4=";
        try {
            File file = new File(saveImage(imageReceiver));
            RequestBody fileBody = RequestBody.create(
                    MediaType.parse("multipart/form-data"), file);
            RequestBody body = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("images", "image", fileBody)
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .header("X-Auth-Token", token)
                    .post(body)
                    .build();
            HttpHelper httpHelper = HttpHelper.getInstance();
            Map<String, Object> res = httpHelper.synchronousExecute(request);
            if ((int) res.get("code") == 200) {
                return toList(String.valueOf(res.get("body")));
            } else {
                return null;
            }
        } catch (Exception e) {
            HiLog.info(TAG, e.getMessage());
        }

        return null;
    }

    public String byImageReceiver(ImageReceiver imageReceiver) {
        // Set Input Data.
        Image image = imageReceiver.readNextImage();
        ByteBuffer imageBuffer = correctionData(image);
        if (imageBuffer == null) {
            HiLog.error(TAG, "Image byteBuffer is null!");
            return null;
        } else if (!modelBuild) {
            HiLog.error(TAG, "Model build failure!");
            return null;
        } else {
            predict(imageBuffer);
        }
        return null;
    }

    /**
     * 将Image数据修正为ByteBuffer
     */
    private ByteBuffer correctionData(Image image) {
        if (image == null) {
            HiLog.error(TAG, "image data is null!");
            return null;
        }
        int height = 224;//image.getImageSize().height/10;
        int width = 224;//image.getImageSize().width/10;
//        将Image转为PixelMap
        Image.Component component = image.getComponent(ImageFormat.ComponentType.JPEG);
        byte[] bytes = new byte[component.remaining()];
        component.read(bytes);
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        options.formatHint = "image/jpeg";
        ImageSource imageSource = ImageSource.create(bytes, options);
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        decodingOptions.desiredSize = new Size(width, height);
        PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);

        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(width * height * 4 * 3);

//        修正数据
        final float[] IMAGE_MEAN = new float[]{0.485f * 255f, 0.456f * 255f, 0.406f * 255f};
        final float[] IMAGE_STD = new float[]{0.229f * 255f, 0.224f * 255f, 0.225f * 255f};

        int index = 0;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                Position position = new Position(j, i);
                int aRGB = pixelMap.readPixel(position);
                RgbColor color = RgbColor.fromArgbInt(aRGB);
                byteBuffer.putFloat(index, (color.getRed() - IMAGE_MEAN[0]) / IMAGE_STD[0]);
                byteBuffer.putFloat(index + 4, (color.getGreen() - IMAGE_MEAN[1]) / IMAGE_STD[1]);
                byteBuffer.putFloat(index + 8, (color.getBlue() - IMAGE_MEAN[2]) / IMAGE_STD[2]);
                index += 4 * 3;
            }
        }
        HiLog.info(TAG, "bytebuffer>>>" + byteBuffer);
        return byteBuffer;
    }

    /**
     * 初始化模型
     */
    private void initModel(String modelPath) {
//        加载模型（.ms）
        FileInputStream fileInputStream;
        RawFileDescriptor rawFileDescriptor;
        try {
            rawFileDescriptor = context.getResourceManager().getRawFileEntry(modelPath).openRawFileDescriptor();
            fileInputStream = new FileInputStream(rawFileDescriptor.getFileDescriptor());
            FileChannel fileChannel = fileInputStream.getChannel();
            long startOffset = rawFileDescriptor.getStartPosition();
            long declaredLen = rawFileDescriptor.getFileSize();
            MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLen).load();
//            buffer.position(Math.toIntExact(startOffset));
            //        配置使用CPU后端
            MSContext msContext = new MSContext();
            if (!msContext.init(2, CpuBindMode.MID_CPU, false)) {
                HiLog.error(TAG, "[MS_LITE]\tmsContext init failure!");
                return;
            } else {
                HiLog.info(TAG, "[MS_LITE]\tmsContext init success!");
            }
            if (!msContext.addDeviceInfo(DeviceType.DT_CPU, false, 0)) {
                HiLog.error(TAG, "[MS_LITE]\tmsContext addDeviceInfo failure!");
                return;
            } else {
                HiLog.info(TAG, "[MS_LITE]\tmsContext addDeviceInfo success!");
            }

            model = new Model();
            modelBuild = model.build(buffer, ModelType.MT_MINDIR, msContext);
            if (!modelBuild) {
                HiLog.info(TAG, "[MS_LITE]\tbuild model failed");
            } else {
                HiLog.info(TAG, "[MS_LITE]\tbuild model success");
            }

        } catch (IOException e) {
            HiLog.error(TAG, "[MS_LITE]\tLoad model failed！");
            HiLog.error(TAG, "[MS_LITE]\t" + e.getMessage());
        }
    }

    /**
     * 进行推理
     */
    private void predict(ByteBuffer imageBuffer) {
        List<MSTensor> inputs = model.getInputs();
        //  int[][] dims = {{1, image.getImageSize().width/10, image.getImageSize().height/10, 3}};
//            if (model.resize(inputs, dims)) {
        MSTensor inputTensor = inputs.get(0);
        if (inputTensor.setData(imageBuffer)) {
            if (model.predict()) {
                List<MSTensor> tensors = model.getOutputs();
                for (MSTensor tensor : tensors) {
                    HiLog.info(TAG, "output size >>>" + tensor.size());
                    float[] output = tensor.getFloatData();
                    HiLog.info(TAG, "output size >>>" + output.length);
                    Set set = new HashSet();
                    for (float f : output) {
                        HiLog.info(TAG, "output item >>>" + f);
                        set.add(f);
                    }
                    HiLog.info(TAG, "output >>>" + set);
                }
            }
        }
//            }
    }

    private String saveImage(ImageReceiver receiver) {
        File saveFile = new File(context.getExternalFilesDir(null), "IMG_" + System.currentTimeMillis() + ".jpg");
        ohos.media.image.Image image = receiver.readNextImage();
        ohos.media.image.Image.Component component = image.getComponent(ImageFormat.ComponentType.JPEG);
        byte[] bytes = new byte[component.remaining()];
        component.read(bytes);
        try (FileOutputStream output = new FileOutputStream(saveFile)) {
            output.write(bytes);
            output.flush();
            String msg = "Take photo succeed, path=" + saveFile.getPath();
            HiLog.info(TAG, msg);
            return saveFile.getPath();
        } catch (IOException e) {
            HiLog.error(TAG, "%{public}s", "saveImage IOException");
        }
        return null;
    }

    private Map<Float, String> toList(String resStr) {
        Map<Float, String> resMap = new TreeMap<>();
        resStr = resStr.split(":")[2]
                .replace(" ", "")
                .replace("\"", "")
                .replace("[[", "")
                .replace("]]}", "");
        String[] strs = resStr.split("\\],\\[");
        for (String s : strs) {
            String[] tempStr = s.split(",");
            resMap.put(Float.parseFloat(tempStr[1]), tempStr[0]);
        }
        return resMap;
    }
}
